package com.vitaf.cash.app.utils.manager

import android.app.Activity
import android.content.Context
import android.content.Context.INPUT_METHOD_SERVICE
import android.os.IBinder
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import java.lang.ref.WeakReference

/**
 * 软键盘管理器
 */
class VitafKeyboardManager(activity: Activity) {

    private val activityRef = WeakReference(activity)
    private var hideOnTouchOutside = true
    private var lastTouchY = 0f

    /**
     * 设置点击外部是否隐藏键盘
     * @param hide 是否隐藏
     */
    fun setHideOnTouchOutside(hide: Boolean) {
        this.hideOnTouchOutside = hide
    }

    /**
     * 隐藏软键盘
     */
    fun hideSoftInput() {
        val activity = activityRef.get() ?: return
        val view = activity.currentFocus ?: activity.window.decorView
        hideSoftInputFrom(view)
    }

    /**
     * 显示软键盘
     * @param view 需要获取焦点的View
     */
    fun showSoftInput(view: View) {
        val activity = activityRef.get() ?: return
        view.requestFocus()
        val imm = activity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        view.postDelayed({
            imm.showSoftInput(view,0)
        },100)
    }

    /**
     * 切换软键盘状态
     * @param view 关联的View
     */
    fun toggleSoftInput(view: View) {
        view.requestFocus()
        val activity = activityRef.get() ?: return
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }

    /**
     * 分发触摸事件（需要在Activity的dispatchTouchEvent中调用）
     * @param event 触摸事件
     * @return 是否已处理
     */
    fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (!hideOnTouchOutside) return false

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchY = event.y
            }
            MotionEvent.ACTION_UP -> {
                // 只在Y轴没有移动时才隐藏键盘（防止与滑动冲突）
                if (lastTouchY == event.y) {
                    val activity = activityRef.get() ?: return false
                    val currentFocus = activity.currentFocus
                    if (currentFocus != null && isTouchOutsideEditText(currentFocus, event)) {
                        hideSoftInputFrom(currentFocus.windowToken)
                    }
                }
            }
        }
        return false
    }

    /**
     * 判断触摸点是否在EditText外部
     * @param view 当前焦点View
     * @param event 触摸事件
     * @return 是否在外部
     */
    private fun isTouchOutsideEditText(view: View, event: MotionEvent): Boolean {
        if (view !is EditText) return true

        val location = IntArray(2)
        view.getLocationOnScreen(location)

        val left = location[0]
        val top = location[1]
        val right = left + view.width
        val bottom = top + view.height

        val x = event.rawX
        val y = event.rawY

        return x < left || x > right || y < top || y > bottom
    }

    /**
     * 隐藏指定View的软键盘
     * @param view 目标View
     */
    private fun hideSoftInputFrom(view: View) {
        val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    /**
     * 隐藏指定WindowToken的软键盘
     * @param token WindowToken
     */
    fun hideSoftInputFrom(token: IBinder?) {
        token ?: return
        val activity = activityRef.get() ?: return
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}